<template>
    <div class="roles-container">
        <!-- 角色列表导航 -->
        <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 角色列表 -->
        <el-card>
                <!-- 角色添加按钮 -->
                <el-row>
                    <el-column>
                        <el-button type="primary">添加角色</el-button>
                    </el-column>
                </el-row>
                <!-- 角色表格渲染 -->
              <el-table :data="roleList" style="width:100%" height="100vh" :default-sort = "{prop: 'level', order: 'descending'}" border stripe>
                <el-table-column type='index'></el-table-column>
                <!-- 展开 列表-->
                <el-table-column type='expand'>
                    <el-template slot-scope="scope">
                          <!-- {{  scope.row}} -->
                        <!-- {{scope.row.children.authName}} -->
                          <!-- 权限渲染布局 -->
                          <el-row :class="['bdbuttom','vcenter','bdleft',i1 == 0 ? 'bdtop':'' ]" v-for="(item1 ,i1) in scope.row.children" :key='i1'>
                          <!-- 一级权限 -->
                                <el-col  :span = '4'>
                                      <el-tag type="primary" >{{item1.authName}}</el-tag>
                                      <i class="el-icon-caret-right"></i>
                                </el-col>
                          <!-- 二级\三级 权限 -->
                                <el-col  :span = '20'>
                                    <el-row v-for="(item2,i2) in item1.children" :class="['vcenter','bdleft','bdright',i2 === 0 ? '' :'bdtop']" :key="i2">
                                        <el-col :span="4">
                                            <el-tag type="success" > {{item2.authName}}</el-tag>
                                             <i class="el-icon-caret-right"></i>
                                        </el-col>
                                        <el-col :span="16" class="vcenter  ">
                                            <el-tag  type="warning" v-for="(item3,i3) in item2.children" :key="i3" size="small" @close="removeRightByid(scope.row,item3.id)" closable>{{item3.authName}} </el-tag>
                                        </el-col>
                                    </el-row>
                                </el-col>
                          </el-row>
                    </el-template>
                </el-table-column>
                <el-table-column prop="id" label="角色ID" width="250%"  ></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"  ></el-table-column>
                <el-table-column prop="roleDesc" label="操作"  >
                    <template slot-scope="scope">
                    <!-- 编辑按钮 -->
                   <el-button type="primary" size="small" icon="el-icon-edit" @click="editRole(scope.row.id)">编辑 </el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" size="small"  icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
                    <!--  分配权限按钮 -->
                    <el-button type="success" size="small" icon="el-icon-s-tools" @click="editRight(scope.row)">分配权限</el-button>
                </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 分配权限对话框 -->
        <el-dialog
            title="分配权限"  :visible.sync="editRightDialog"  width="50%" @close = 'setRightDialogClosed'>
            <!-- 对话框主体 -->
            <!-- 搜索框 -->
            <el-input  placeholder="输入关键字进行搜索" v-model="filterRightText" class="filterRightinput"> </el-input>
            <!-- 权限树 -->
            <el-tree :data="rightList" :props="treeProps" :filter-node-method="filterRightNode" ref="rightTreeRef"  
             show-checkbox  default-expand-all  :default-checked-keys="defkeys" node-key='id'></el-tree>
            <!--  -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRightDialog = false">取 消</el-button>
                <el-button type="primary" @click="allotRight()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data(){
        return{
            // 所有角色
            roleList:[],
            // 所有权限
            rightList:[],
            // 分配权限对话框显示与隐藏变量
            editRightDialog : false,
            // 权限搜索input值绑定
             filterRightText:'',
            // 树形控件树形绑定对象
            treeProps:{
               label: 'authName',
              children: 'children'
            },
            // 默认选中权限的数组
            defkeys:[],
            roleid:'',
        }
    },
    created(){
        this.getRoleList();
    },
    watch: {
      filterRightText(val) {
        this.$refs.rightTreeRef.filter(val);
        
        
      }
    },
    methods:{
        // 获取角色列表请求数据
        async getRoleList(){
           const {data:res} = await this.$http.get('roles')
           if(res.meta.status !== 200 ) return this.$Message.error('角色列表获取失败！')
            this.roleList = res.data;
           this.$Message.success('角色列表获取成功！')
        },
        // 删除三级权限
        removeRightByid( role,rightId){
            this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then( async () => {
                const {data:res} =  await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if(res.meta.status !==200) return this.$message.error('权限删除失败')
                this.$message.success('权限删除成功');
                // 重新获取三级权限 数据双向绑定给scope.row
                // this.getRoleList();
                role.children = res.data;
                }).catch(() => {
                    this.$message({
                    type: 'info',
                    message: '已取消权限删除操作'
                });          
            });
        },
        //修改角色
        editRole(id){},
        // 删除角色
        deleteRole(){},
        // 分配权限
       async  editRight(role){
            //    赋值默认勾选权限的id
            this.getLeafKeys(role,this.defkeys);
            // 保存角色id
            this.roleid = role.id;
            //    权限弹窗显示
              this.editRightDialog = true;
              const {data : res} = await this.$http.get('/rights/tree')
              if(res.meta.status !== 200) return this.$$Message.error('权限获取失败！')

              this.$Message.success('权限获取成功！')
              this.rightList = res.data;
             
        },  
        // 筛选权限方法
        filterRightNode(value, data) {
            if (!value) return true;
            return data.authName.indexOf(value) !== -1;
         },
        //  递归函数获取角色下三级所有权限的id
        getLeafKeys(node,arr){
            //若当前节点不包含children属性，表示是三级节点
            if(!node.children) {
                return  arr.push(node.id);
                }
            node.children.forEach(item =>{
                this.getLeafKeys(item, arr)

            })

            
        },
        // 监听权限对话框关闭,将勾选的重置为空
        setRightDialogClosed(){
            this.defkeys = []
        },
        // 分配权限确定按钮，修改数据库中的数据并保存
       async allotRight(role){
            // 把选中的节点组成新数组
            const keys = [...this.$refs.rightTreeRef.getCheckedNodes(),
                          ...this.$refs.rightTreeRef.getHalfCheckedNodes() 
                         ];
           //  获取id字符串
            const keysIdarr = [];
               keys.forEach(item =>  keysIdarr.push(item.id) )    
           const idStr = keysIdarr.join(',');    
             // 更新勾选权限请求
            const {data : res } = await  this.$http.post(`roles/${this.roleid}/rights`,
                {
                rids:idStr
                })
          
          if(res.meta.status !== 200) return this.$Message.error('权限分配失败！')
            this.$Message.success('权限分配成功！');
            //   重新获取角色列表数据
             this.getRoleList();
            //    关闭对话框
            this.editRightDialog = false;
       }
    }
}
</script>
<style lang="less" scoped>
.el-card{
    box-shadow:0 0 3px #ddd;
    margin-top:20px;
    .el-table{
        margin-top:20px;
        .el-button{
            padding-left:8px;
            padding-right:10px;
            text-align: center;
        }
    }
}
.el-row{
   
    .el-tag{
        margin :10px 5px;
    }
}

.bdtop{
    border-top: 1px solid #eee;
}
.bdbuttom{
    border-bottom: 1px solid #eee;
    
}
.bdleft{
     border-left:1px solid #eee;
}
.bdright{
     border-right:1px solid #eee;
}
.vcenter {
    display: flex;
    align-items: center;
}
.filterRightinput{
    margin-top:-40px;
    margin-bottom:10px;
}
</style>